<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, provide, Ref, ref } from "vue";
import { useRoute } from "vue-router";
import { storeToRefs } from "pinia";
import { io } from "socket.io-client";
import type { Socket } from "socket.io-client";
import type { UserInfo } from "@/types/userTypes";
import type { RouteLocationNormalized } from "vue-router";
import type { TimeMessages, Message as MessageInfo, ConsultOrderItem } from "@/types/chitchat";
import type { Image } from "@/types/consultTypes";
import { MsgType, OrderType } from "@/enum";
import { baseURL } from "@/utils/request.ts";
import { getUserInfo } from "@/utils/localStorage.ts";
import useConsultStore from "@/pinia/modules/consultStore.ts";
import useUserStore from "@/pinia/modules/userStore.ts";
import Status from "@/views/home/procedure/chitchat/components/status/status.vue";
import Message from "@/views/home/procedure/chitchat/components/message/message.vue";
import Action from "@/views/home/procedure/chitchat/components/action/action.vue";


const route: RouteLocationNormalized = useRoute();

const consultStore = useConsultStore();

const userStore = useUserStore();

/*修改评价状态的回调函数*/
const completeEva = (score: number) => {
    const item = messageList.value.find((item) => item.msgType === MsgType.CardEvaForm);
    if (item) {
        item.msg.evaluateDoc = { score };
        item.msgType = MsgType.CardEva;
    }
};


const { orderDetail } = storeToRefs(consultStore);

provide<Ref<ConsultOrderItem>>("orderDetail", orderDetail);

provide<(score: number) => void>("completeEva", completeEva);

/*聊天列表*/
const messageList = ref<MessageInfo[]>([]);

/*
* 导入socket.ic插件
* 初始化创建wx长连接(打电话)
* 1.通过io函数传入后台ws链接地址和相关参数
* 2.连接建立成功后的相关事件
*  -通过io实例的connect事件，监听连接是否成功
*  -通过io实例的error事件，监听连接是否错误
*  -通过io实例的disconnect事件，监听连接断开
* */
/*socket实例*/
let socket: Socket;
/*初始化socket的函数*/
const initSocket = () => {
    socket = io(baseURL, {
        auth: {
            token: `Bearer ${getUserInfo<UserInfo>().token}`,
        },
        query: {
            orderId: route.query.orderId,
        },
    });
    socket.on("connect", () => {
        console.log("socket连接成功");
    });
    socket.on("error", () => {
        console.log("socket连接失败");
    });
    socket.on("disconnect", () => {
        console.log("socket断开连接");
    });
    // 接收wx服务器给浏览器发送的默认数据
    socket.on("chatMsgList", ({ data }: { data: TimeMessages[] }) => {
        const result: MessageInfo[] = [];
        data.forEach((item) => {
            result.push({ id: item.createTime, msgType: MsgType.Notify, msg: { content: item.createTime } } as MessageInfo);
            result.push(...item.items);
        });
        messageList.value.push(...result);
    });

    // 接收医生消息
    socket.on("receiveChatMsg", async (event: MessageInfo) => {
        messageList.value.push(event);
        await nextTick();
        window.scrollTo(0, document.body.scrollHeight);
    });

    //接收订单变化的消息
    socket.on("statusChange", () => {
        // 发送请求重新获取订单详情
        consultStore.fetchConsultOrderDetail(route.query.orderId as string);
    });

};


const getText = (text: string) => {
    socket.emit("sendChatMsg", {
        from: userStore.userInfo?.id,
        to: consultStore.orderDetail.docInfo?.id,
        msgType: MsgType.MsgText,
        msg: { content: text },
    });
};


const getImg = (img: Image) => {
    socket.emit("sendChatMsg", {
        from: userStore.userInfo?.id,
        to: orderDetail.value?.docInfo?.id,
        msgType: MsgType.MsgImage,
        msg: { picture: img },
    });
};

onMounted(() => {
    // 初始化socket
    initSocket();
});

onMounted(() => {
    // 获取订单详情
    consultStore.fetchConsultOrderDetail(route.query.orderId as string);
});

onBeforeUnmount(() => {
    // 关闭socket
    socket.close();
});
</script>

<template>
    <div class="chitchat">
        <nav-bar title="问诊室" fixed left-arrow left-text="返回" @click-left="$router.replace('/')" />
        <status :status="orderDetail.status" :countdown="orderDetail.countdown"></status>
        <message v-for="(message) in messageList" :key="message.id" :message="message"></message>
        <action :disabled="orderDetail?.status !== OrderType.ConsultChat" @sendText="getText" @sendImg="getImg"></action>
    </div>
</template>

<style scoped lang="scss">
.chitchat {
    padding-bottom: 60px;
    padding-top: 100px;
    min-height: 100vh;
    box-sizing: border-box;
    background-color: var(--cp-bg);

    .van-pull-refresh {
        width: 100%;
        min-height: calc(100vh - 150px);
    }
}
</style>
